package com.heo.coder.packet.base;

import java.util.Date;

import com.heo.util.ByteHelper;

public abstract class BasePacket {

	public static final String PASS = "01020304";
	public static final int START_MARKER_LENGTH = 2;// 标识位长度
	public static final String START_MARKER_LENGTH_CODE = "AAAA";// 标识位内容
	public static final int CRC_MARKER_LENGTH = 2;// 标识位长度
	public static final int CMD_MARKER_LENGTH = 1;// 标识位长度
	public static final int CHECK_LENGTH = 1;
	public static final int HEAD_LENGTH = 4;// 消息头长度

	protected String control = ""; // 加密1位 0不加密 
	protected String lengthStr = "";
	protected int bodyLength = 0; // 消息体长度 
	public String body = ""; // 具体数据 16进制数据
	protected String check = ""; // 校验位 长度1 2字节 校验码指从消息头开始，同后一字节异或，直到效验码前一个字节，占用一个字节
	protected byte[] checkSum = new byte[] {0, 0};
	protected Date createTime = new Date();


	public int getTotleLength() {
		return START_MARKER_LENGTH + CHECK_LENGTH + CRC_MARKER_LENGTH + CMD_MARKER_LENGTH + bodyLength;
	}

	/**
	 * 根据数据包构造对象
	 */
	public BasePacket(String lengthStr, int bodyLength,
			String check, String control, String body) throws Exception {
		this.lengthStr = lengthStr;
		this.check = check;
		this.control = control;
		this.bodyLength = bodyLength; 
		this.body = body;
	}

	public abstract String getPacketBody();

	/**
	 * 获得整个数据包
	 * 
	 * @return
	 */
	public byte[] getPacket() {
		return ByteHelper.margeByte(
				ByteHelper.hexStringToBytes(START_MARKER_LENGTH_CODE), 
				ByteHelper.hexStringToBytes(lengthStr),  
//				ByteHelper.hexStringToBytes(check), 
				checkSum, 
				ByteHelper.hexStringToBytes(control), 
				ByteHelper.hexStringToBytes(body));
	}

	public void checkData() {
		byte[] checksum = ByteHelper.checkSum(getPacket(), PASS);
		check = ByteHelper.byteToHexStringNoSpace(checksum);
		checkSum = checksum;
	}
	
	public int getBodyLength() {
		return bodyLength;
	}

	public void setBodyLength(int bodyLength) {
		this.bodyLength = bodyLength;
	}

	
	public String getBody() {
		return body;
	}

	public void setBody(String body) {
		this.body = body;
	}

	public String getCheck() {
		return check;
	}

	public void setCheck(String check) {
		this.check = check;
	}

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public String getControl() {
		return control;
	}

	public void setControl(String control) {
		this.control = control;
	} 

	public String getLengthStr() {
		return lengthStr;
	}

	public void setLengthStr(String lengthStr) {
		this.lengthStr = lengthStr;
	}
}
